// index/pages/questionAnalysis/questionAnalysis.js

// 导入必要的服务模块
const { http } = require('../../../utils/http.js');
const { noteService } = require('../../../utils/noteService.js');
const { userService } = require('../../../utils/userService');

Page({
  data: {
    // 页面标题
    pageTitle: '题目解析',
    
    // 答题报告数据
    reportData: {
      total: 0,
      correct: 0,
      wrong: 0,
      unanswered: 0,
      correctRate: 0,
      totalTime: '',
      completeTime: '',
      questionBankName: ''
    },
    
    // 题目列表
    questions: [],
    
    // 当前题目索引
    currentIndex: 0,
    
    // 当前题目数据
    currentQuestion: {},
    
    // 答题状态数组
    answerStatus: [],
    
    // 显示控制
    showOptions: true,
    showResult: true,
    showAnalysis: true,
    
    // 当前标签页
    activeTab: 'analysis',
    
    // 评论和笔记
    commentText: '',
    noteText: '',
    
    // 评论列表
    comments: [],
    
    // 题库ID
    questionBankId: null
  },

  onLoad(options) {
    
    // 获取传递的答题数据
    if (options.reportData) {
      try {
        const reportData = JSON.parse(decodeURIComponent(options.reportData));

        
        // 根据模式设置页面标题
        let pageTitle = '题目解析';
        if (reportData.mode === 'wrong') {
          pageTitle = '错题解析';
        } else if (reportData.mode === 'review') {
          pageTitle = '全部解析';
        }
        

        
        // 设置页面数据
        const answerStatus = reportData.answerStatus || reportData.wrongQuestions || [];

        
        this.setData({ 
          pageTitle,
          reportData,
          answerStatus: answerStatus,
          questionBankId: reportData.questionBankId
        });
        

        this.fetchRealQuestionData();
        
      } catch (e) {
        console.error('\n❌ === 解析答题数据失败 ===', e);
        console.error('错误详情:', e.message);
        console.error('错误堆栈:', e.stack);
        wx.showToast({ title: '数据解析失败', icon: 'error' });
      }
    } else if (options.questionId) {
      // 接收单个题目ID
      const questionId = options.questionId;
      const pageTitle = options.pageTitle || '题目解析';
      
      console.log('接收单个题目ID:', questionId);
      
      // 构建单个题目的答题状态
      const answerStatus = [{
        questionNumber: 1,
        status: 'review', // 复习模式
        originalIndex: 0,
        questionId: questionId
      }];
      
      this.setData({ 
        pageTitle,
        answerStatus: answerStatus,
        questionBankId: null
      });
      
      this.fetchRealQuestionData();
      
    } else {
      wx.showToast({ title: '缺少题目数据', icon: 'error' });
    }
  },

  /**
   * 尝试获取真实题目数据
   */
  fetchRealQuestionData() {
    const { answerStatus } = this.data;
    
    if (!Array.isArray(answerStatus) || answerStatus.length === 0) {
      return;
    }

    console.log('开始获取真实题目数据，答题状态:', answerStatus);

    // 直接构建题目列表，通过题目ID获取真实数据
    this.buildQuestionsList(answerStatus);
    
    // 如果是单个题目，直接加载第一题数据
    if (answerStatus.length === 1) {
      console.log('单个题目模式，直接加载第一题数据');
      // 延迟一下，确保题目列表构建完成
      setTimeout(() => {
        this.loadQuestionData(0);
      }, 100);
    }
  },

  /**
   * 从API获取题目数据
   */
  fetchQuestionsFromAPI(questionBankId) {
    
    // 显示加载提示
    wx.showLoading({ title: '加载题目数据...' });
    
    // 调用题目API获取真实数据
    // 这里需要根据你的实际API接口来修改
    const { http } = require('../../../utils/http.js');
    
    http.get(`/fk/question_bank/questions/${questionBankId}`)
      .then(res => {
        wx.hideLoading();
        
        if (res && res.data) {
          const questions = res.data;

          
          // 存储到本地存储
          try {
            const storageKey = `questions_${questionBankId}`;
            wx.setStorageSync(storageKey, questions);

          } catch (e) {
            console.error('存储题目数据失败:', e);
          }
          
          // 重新构建题目列表
          this.buildQuestionsList(this.data.answerStatus);
        } else {
          console.warn('API返回数据格式异常:', res);
          // 回退到本地存储
          this.buildQuestionsList(this.data.answerStatus);
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('API获取题目数据失败:', err);
        
        // API调用失败，回退到本地存储
        wx.showToast({ 
          title: '网络请求失败，使用本地数据', 
          icon: 'none',
          duration: 2000
        });
        
        this.buildQuestionsList(this.data.answerStatus);
      });
  },

  /**
   * 构建题目列表
   */
  buildQuestionsList(answerStatus) {
    if (!Array.isArray(answerStatus) || answerStatus.length === 0) {
      return;
    }

    console.log('构建题目列表，答题状态:', answerStatus);

    // 构建题目列表，先创建基础结构
    const questions = answerStatus.map((item, index) => {
      const question = {
        id: item.questionId,
        question_id: item.questionId,
        title: `第${item.questionNumber}题`,
        content: '加载中...', // 临时占位
        type: '单选题',
        index: index,
        status: item.status,
        questionNumber: item.questionNumber,
        originalIndex: item.originalIndex,
        options: [], // 临时空数组
        correctAnswer: '',
        analysis: '加载中...', // 临时占位
        explanation: '加载中...', // 临时占位
        comments: [], // 临时空数组
        notes: [] // 临时空数组
      };
      
      return question;
    });

    console.log('构建的题目列表:', questions);

    this.setData({ 
      questions,
      totalQuestions: questions.length
    });

    // 依次获取每个题目的真实数据
    this.fetchAllQuestionDetails(questions);
  },

  /**
   * 获取所有题目的详细数据 - 优化版本：先显示题目和选项，再异步加载评论和解析
   */
  fetchAllQuestionDetails(questions) {
    const { answerStatus } = this.data;
    
    // 显示加载提示
    wx.showLoading({ title: '加载题目数据...' });
    
    let completedCount = 0;
    const totalQuestions = questions.length;
    
    // 为每个题目获取详细数据
    answerStatus.forEach((item, index) => {
      const questionId = item.questionId;

      // 先获取题目详情和选项（用户最需要的内容）
      Promise.all([
        this.fetchQuestionDetail(questionId),
        this.fetchQuestionOptions(questionId)
      ]).then(([detail, options]) => {

        console.log(`题目ID ${questionId} 基础数据获取成功:`, { detail, options });
        
        // 先更新题目基础数据（题目内容和选项）
        const updatedQuestion = {
          ...questions[index],
          ...detail,
          options: this.markCorrectOption(options.options || options, detail.correctAnswer),
          analysis: options.analysis || detail.analysis || '加载中...', // 先显示加载中
          comments: [] // 先设为空数组
        };
        
        console.log(`更新后的题目基础数据:`, updatedQuestion);
        
        // 更新questions数组
        const updatedQuestions = [...this.data.questions];
        updatedQuestions[index] = updatedQuestion;
        
        this.setData({ questions: updatedQuestions });
        
        // 如果是当前显示的题目，立即更新currentQuestion
        if (index === this.data.currentIndex) {
          this.setData({ currentQuestion: updatedQuestion });
          console.log('当前题目基础数据已更新，用户可以立即看到题目和选项');
        }
        
        // 如果是第一题，立即显示
        if (index === 0) {
          this.loadQuestionData(0);
          wx.hideLoading(); // 第一题加载完成就隐藏loading
        }
        
        // 异步获取评论（不影响用户体验）
        this.fetchQuestionComments(questionId).then(comments => {
          console.log(`题目ID ${questionId} 评论获取成功:`, comments);
          
          // 更新评论数据
          const finalQuestion = {
            ...updatedQuestion,
            comments: comments
          };
          
          const finalQuestions = [...this.data.questions];
          finalQuestions[index] = finalQuestion;
          
          this.setData({ questions: finalQuestions });
          
          // 如果是当前显示的题目，更新currentQuestion
          if (index === this.data.currentIndex) {
            this.setData({ currentQuestion: finalQuestion });
            console.log('当前题目评论数据已更新');
          }
        }).catch(err => {
          console.error(`❌ 题目ID ${questionId} 评论获取失败:`, err);
          // 评论获取失败不影响主要功能
        });
        
        completedCount++;
        
        // 检查是否所有题目基础数据都加载完成
        if (completedCount === totalQuestions) {
          console.log('所有题目基础数据加载完成');
          
          // 输出所有题目的汇总信息
          this.outputQuestionsSummary(updatedQuestions);
        }
      }).catch(err => {
        console.error(`❌ 题目ID ${questionId} 基础数据获取失败:`, err);
        completedCount++;
        
        // 即使失败也要检查是否完成
        if (completedCount === totalQuestions) {
          wx.hideLoading();
          console.log('部分题目数据加载失败，但继续处理');
          
          // 输出所有题目的汇总信息
          this.outputQuestionsSummary(this.data.questions);
          
          // 加载第一题数据
          if (this.data.questions.length > 0) {
            this.loadQuestionData(0);
          }
        }
      });
    });
  },

  /**
   * 输出所有题目的汇总信息
   */
  outputQuestionsSummary(questions) {
    // 汇总信息已移除，但保留方法调用以确保数据更新完成
    console.log('题目数据加载完成，共', questions.length, '道题');
  },

  /**
   * 获取题目详情
   */
  fetchQuestionDetail(questionId) {
    const { http } = require('../../../utils/http.js');
    
    // 检查题目ID是否有效
    if (!questionId || questionId === `q_${questionId}` || questionId.toString().startsWith('q_')) {
      console.warn(`⚠️ 题目ID无效或为默认值: ${questionId}`);
      return Promise.resolve({
        content: `题目ID: ${questionId} - 无效的题目ID`,
        type: '单选题',
        analysis: '题目ID无效',
        explanation: '题目ID无效',
        correctAnswer: 'A'
      });
    }
    
    return http.get(`/fk/question/${questionId}`)
      .then(res => {

        console.log(`题目详情API响应 - ID: ${questionId}:`, res);
        
        if (res && res.data) {
          // 检查响应状态
          if (res.code === 500) {
            console.error('获取题目详情失败 - 后端错误:', res);
            return {
              content: `题目ID: ${questionId} - 后端服务错误`,
              type: '单选题',
              analysis: '后端服务错误',
              explanation: '后端服务错误',
              correctAnswer: 'A'
            };
          }
          

          
          // 尝试多种可能的字段名
          const possibleContentFields = ['content', 'stem', 'question', 'title', 'text', 'body', 'description'];
          const possibleTypeFields = ['type', 'questionType', 'question_type', 'category'];
          const possibleAnalysisFields = ['analysis', 'explain', 'questionAnalysis', 'explanation', 'answer', 'solution'];
          const possibleAnswerFields = ['correctAnswer', 'answer', 'correct_answer', 'rightAnswer', 'solution'];
          
          let content = '';
          let type = '单选题';
          let analysis = '';
          let explanation = '';
          let correctAnswer = 'A';
          
          // 查找内容字段
          for (const field of possibleContentFields) {
            if (res.data[field] && res.data[field].toString().trim()) {
              content = res.data[field].toString().trim();

              break;
            }
          }
          
          // 查找类型字段
          for (const field of possibleTypeFields) {
            if (res.data[field]) {
              const typeValue = res.data[field].toString();

              
              // 转换类型值
              if (typeValue === 'SINGLE' || typeValue === 'single') {
                type = '单选题';
              } else if (typeValue === 'MULTIPLE' || typeValue === 'multiple') {
                type = '多选题';
              } else if (typeValue === 'JUDGE' || typeValue === 'judge') {
                type = '判断题';
              } else {
                type = typeValue;
              }
              break;
            }
          }
          
          // 查找解析字段
          for (const field of possibleAnalysisFields) {
            if (res.data[field] && res.data[field].toString().trim()) {
              analysis = res.data[field].toString().trim();

              break;
            }
          }
          
          // 查找答案字段
          for (const field of possibleAnswerFields) {
            if (res.data[field]) {
              correctAnswer = res.data[field].toString();

              break;
            }
          }
          
          // 如果没有找到内容，尝试其他方法
          if (!content) {
            // 检查是否有其他可能包含内容的字段
            const allFields = Object.keys(res.data);
            for (const field of allFields) {
              const value = res.data[field];
              if (value && typeof value === 'string' && value.length > 10 && !field.includes('id') && !field.includes('time')) {
                if (!content) {
                  content = value;
                }
              }
            }
          }
          
          // 如果仍然没有内容，使用默认值
          if (!content) {
            content = `题目ID: ${questionId} - 暂无题目内容`;
          }
          
          const result = {
            content: content,
            type: type,
            analysis: analysis || '暂无解析',
            explanation: explanation || analysis || '暂无解析说明',
            correctAnswer: correctAnswer || 'A'
          };
          

          return result;
          
        } else {
          console.warn(`⚠️ 题目详情数据异常 - ID: ${questionId}`, res);
          return {
            content: `题目ID: ${questionId} - 数据加载失败`,
            type: '单选题',
            analysis: '数据加载失败',
            explanation: '数据加载失败',
            correctAnswer: 'A'
          };
        }
      })
      .catch(err => {
        console.error(`❌ 获取题目详情失败 - ID: ${questionId}`, err);
        console.error('错误详情:', err.message);
        console.error('错误堆栈:', err.stack);
        return {
          content: `题目ID: ${questionId} - 网络请求失败: ${err.message}`,
          type: '单选题',
          analysis: '网络请求失败',
          explanation: '网络请求失败',
          correctAnswer: 'A'
        };
      });
  },

  /**
   * 获取题目选项
   */
  fetchQuestionOptions(questionId) {
    const { http } = require('../../../utils/http.js');
    
    // 检查题目ID是否有效
    if (!questionId || questionId === `q_${questionId}` || questionId.toString().startsWith('q_')) {
      console.warn(`⚠️ 题目ID无效或为默认值: ${questionId}`);
      return Promise.resolve({
        options: [
          { label: 'A', text: '题目ID无效', isCorrect: false, isSelected: false },
          { label: 'B', text: '题目ID无效', isCorrect: false, isSelected: false },
          { label: 'C', text: '题目ID无效', isCorrect: false, isSelected: false },
          { label: 'D', text: '题目ID无效', isCorrect: false, isSelected: false }
        ],
        analysis: '暂无解析'
      });
    }
    
    return http.get(`/ssh/questionOption/queryByQuestionId/${questionId}`)
      .then(res => {

        console.log(`题目选项API响应 - ID: ${questionId}:`, res);
        
        // 检查响应状态
        if (res && res.code === 500) {
          console.error('获取选项失败 - 后端错误:', res);
          // 返回默认选项
          return {
            options: [
              { label: 'A', text: '选项A', isCorrect: false, isSelected: false },
              { label: 'B', text: '选项B', isCorrect: false, isSelected: false },
              { label: 'C', text: '选项C', isCorrect: false, isSelected: false },
              { label: 'D', text: '选项D', isCorrect: false, isSelected: false }
            ],
            analysis: '暂无解析'
          };
        }
        
        const options = (res && res.data) ? res.data : res;
        
        if (options && Array.isArray(options)) {

          
          // 转换选项格式，模仿chapterPractice的buildOptionsFromBackendOptions方法
          const labels = ['A', 'B', 'C', 'D', 'E', 'F'];
          const stdOptions = options.slice(0, labels.length).map((opt, i) => {
            const text = opt.text || opt.content || opt.optionText || opt.title || '';
            const rawCorrect = opt.isCorrect || opt.correct || opt.isRight || false;
            const isCorrect = rawCorrect === true || rawCorrect === 1 || rawCorrect === '1' || String(rawCorrect).toLowerCase() === 'true';
            
            return { 
              label: labels[i], 
              text: text || `选项${labels[i]}`, 
              isCorrect: isCorrect, 
              isSelected: false 
            };
          });
          

          return {
            options: stdOptions,
            analysis: '暂无解析' // 数组格式通常没有analysis字段
          };
          
        } else if (options && typeof options === 'object' && options !== null) {

          
          // 处理对象格式的选项数据（optionA, optionB, optionC, optionD等）
          const labels = ['A', 'B', 'C', 'D', 'E', 'F'];
          const optionFields = ['optionA', 'optionB', 'optionC', 'optionD', 'optionE', 'optionF'];
          const correctOptions = options.correctOptions || options.correctAnswer || '';
          
          const stdOptions = optionFields.map((field, i) => {
            const text = options[field] || '';
            if (!text) return null; // 跳过空的选项
            
            // 判断是否为正确答案
            const isCorrect = correctOptions.includes(labels[i]) || correctOptions === labels[i];
            
            return { 
              label: labels[i], 
              text: text, 
              isCorrect: isCorrect, 
              isSelected: false 
            };
          }).filter(Boolean); // 过滤掉空的选项
          

          return {
            options: stdOptions,
            analysis: options.analysis || '暂无解析' // 从选项接口获取解析
          };
          
        } else {
          console.warn(`⚠️ 题目选项数据异常 - ID: ${questionId}`, res);
          return {
            options: [
              { label: 'A', text: '选项A', isCorrect: false, isSelected: false },
              { label: 'B', text: '选项B', isCorrect: false, isSelected: false },
              { label: 'C', text: '选项C', isCorrect: false, isSelected: false },
              { label: 'D', text: '选项D', isCorrect: false, isSelected: false }
            ],
            analysis: '暂无解析'
          };
        }
      })
      .catch(err => {
        console.error(`❌ 获取题目选项失败 - ID: ${questionId}`, err);
        console.error('错误详情:', err.message);
        console.error('错误堆栈:', err.stack);
        return {
          options: [
            { label: 'A', text: '选项A', isCorrect: false, isSelected: false },
            { label: 'B', text: '选项B', isCorrect: false, isSelected: false },
            { label: 'C', text: '选项C', isCorrect: false, isSelected: false },
            { label: 'D', text: '选项D', isCorrect: false, isSelected: false }
          ],
          analysis: '暂无解析'
        };
      });
  },

  /**
   * 获取题目评论
   */
  fetchQuestionComments(questionId) {
    const { http } = require('../../../utils/http.js');
    
    // 检查题目ID是否有效
    if (!questionId || questionId === `q_${questionId}` || questionId.toString().startsWith('q_')) {
      console.warn(`⚠️ 题目ID无效或为默认值: ${questionId}`);
      return Promise.resolve([]);
    }
    
    return http.get(`/wjq/comment/listByQuestionId/${questionId}`)
      .then(res => {

        
        // 检查响应状态
        if (res && res.code === 500) {
          console.error('获取评论失败 - 后端错误:', res);
          // 评论加载失败，但不影响主要功能，返回空数组
          return [];
        }
        
        const comments = (res && res.data) ? res.data : res;
        
        if (comments && Array.isArray(comments)) {

          
          // 转换评论格式，模仿chapterPractice的处理方式
          const stdComments = comments.map((comment, index) => {
            // 尝试多种可能的字段名
            const possibleIdFields = ['id', 'commentId', 'comment_id', 'cid'];
            const possibleUserFields = ['userName', 'user', 'author', 'username', 'nickname', 'name'];
            const possibleContentFields = ['content', 'comment', 'text', 'message', 'body'];
            const possibleTimeFields = ['createTime', 'time', 'createDate', 'create_time', 'updateTime', 'date'];
            
            let id = '';
            let user = '匿名用户';
            let content = '';
            let time = new Date().toLocaleString();
            
            // 查找ID字段
            for (const field of possibleIdFields) {
              if (comment[field]) {
                id = comment[field].toString();
                break;
              }
            }
            
            // 查找用户字段
            for (const field of possibleUserFields) {
              if (comment[field] && comment[field].toString().trim()) {
                user = comment[field].toString().trim();
                break;
              }
            }
            
            // 查找内容字段
            for (const field of possibleContentFields) {
              if (comment[field] && comment[field].toString().trim()) {
                content = comment[field].toString().trim();
                break;
              }
            }
            
            // 查找时间字段
            for (const field of possibleTimeFields) {
              if (comment[field]) {
                const timeValue = comment[field];
                
                // 尝试解析时间
                try {
                  if (typeof timeValue === 'string') {
                    const parsedTime = new Date(timeValue);
                    if (!isNaN(parsedTime.getTime())) {
                      time = parsedTime.toLocaleString();
                    } else {
                      time = timeValue;
                    }
                  } else if (typeof timeValue === 'number') {
                    const parsedTime = new Date(timeValue);
                    if (!isNaN(parsedTime.getTime())) {
                      time = parsedTime.toLocaleString();
                    } else {
                      time = timeValue.toString();
                    }
                  } else {
                    time = timeValue.toString();
                  }
                } catch (e) {
                  console.warn(`⚠️ 评论${index + 1}时间解析失败:`, e);
                  time = timeValue.toString();
                }
                break;
              }
            }
            
            // 如果没有找到内容，使用默认值
            if (!content) {
              content = '暂无评论内容';
            }
            
            return {
              id: id || Date.now() + index,
              user: user,
              content: content,
              time: time
            };
          });
          

          return stdComments;
          
        } else {
          console.warn(`⚠️ 题目评论数据异常 - ID: ${questionId}`, res);
          return [];
        }
      })
      .catch(err => {
        console.error(`❌ 获取题目评论失败 - ID: ${questionId}`, err);
        console.error('错误详情:', err.message);
        console.error('错误堆栈:', err.stack);
        // 评论加载失败不影响主要功能，返回空数组
        return [];
      });
  },

  /**
   * 加载题目数据
   */
  loadQuestionData(index) {
    if (index < 0 || index >= this.data.questions.length) {
      return;
    }

    const question = this.data.questions[index];
    const answerItem = this.data.answerStatus[index];
    
    console.log('加载题目数据，索引:', index, '题目:', question);
    
    // 检查题目基础数据是否已加载
    if (!question.content || question.content === '加载中...') {
      console.log('题目内容未加载，显示加载状态');
      // 显示加载状态
      this.setData({
        currentIndex: index,
        currentQuestion: {
          ...question,
          content: '加载中...',
          options: [
            { label: 'A', text: '加载中...', isCorrect: false, isSelected: false },
            { label: 'B', text: '加载中...', isCorrect: false, isSelected: false },
            { label: 'C', text: '加载中...', isCorrect: false, isSelected: false },
            { label: 'D', text: '加载中...', isCorrect: false, isSelected: false }
          ]
        }
      });
      
      // 异步获取题目数据
      const questionId = question.id || question.question_id;
      if (questionId) {
        Promise.all([
          this.fetchQuestionDetail(questionId),
          this.fetchQuestionOptions(questionId)
        ]).then(([detail, options]) => {
          const updatedQuestion = {
            ...question,
            ...detail,
            options: this.markCorrectOption(options.options || options, detail.correctAnswer),
            analysis: options.analysis || detail.analysis || '暂无解析'
          };
          
          // 更新questions数组
          const updatedQuestions = [...this.data.questions];
          updatedQuestions[index] = updatedQuestion;
          
          this.setData({
            questions: updatedQuestions,
            currentQuestion: updatedQuestion
          });
          console.log('题目数据异步加载完成');
        }).catch(err => {
          console.error('题目数据加载失败:', err);
          wx.showToast({ title: '题目加载失败', icon: 'none' });
        });
      }
    } else if (!question.options || question.options.length === 0) {
      console.log('选项数据未加载，重新获取');
      // 如果选项未加载，重新获取
      this.fetchQuestionOptions(question.id || question.question_id).then(options => {
        const updatedQuestion = { 
          ...question, 
          options: this.markCorrectOption(options.options || options, question.correctAnswer),
          analysis: options.analysis || question.analysis || '暂无解析'
        };
        
        // 更新questions数组
        const updatedQuestions = [...this.data.questions];
        updatedQuestions[index] = updatedQuestion;
        
        this.setData({
          questions: updatedQuestions,
          currentQuestion: updatedQuestion
        });
        console.log('选项数据更新完成');
      });
    } else {
      console.log('题目数据已加载，直接设置');
      // 设置当前题目
      this.setData({
        currentIndex: index,
        currentQuestion: question
      });
    }
  },

  /**
   * 上一题
   */
  prevQuestion() {
    if (this.data.currentIndex <= 0) {
      wx.showToast({ title: '已是第一题', icon: 'none' });
      return;
    }
    const prevIndex = this.data.currentIndex - 1;
    this.loadQuestionData(prevIndex);
  },

  /**
   * 下一题
   */
  nextQuestion() {
    if (this.data.currentIndex >= this.data.questions.length - 1) {
      wx.showToast({ title: '已是最后一题', icon: 'none' });
      return;
    }
    const nextIndex = this.data.currentIndex + 1;
    this.loadQuestionData(nextIndex);
  },

  /**
   * 跳转到指定题目
   */
  jumpToQuestion(e) {
    const number = e.currentTarget.dataset.number;
    const index = number - 1;
    if (index >= 0 && index < this.data.questions.length) {
      this.loadQuestionData(index);
    }
  },

  /**
   * 切换标签页
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });

    // 如果切换到考友点评标签页，获取评论数据
    if (tab === 'comments') {
      this.fetchComments();
    }

    // 如果切换到我的笔记标签页，获取笔记数据
    if (tab === 'notes') {
      this.fetchNote();
    }
  },

  /**
   * 添加评论
   */
  async addComment() {
    if (!this.data.commentText.trim()) {
      wx.showToast({ title: '请输入评论内容', icon: 'none' });
      return;
    }

    const currentQuestion = this.data.currentQuestion;
    const questionId = currentQuestion.id || currentQuestion.question_id;

    if (!questionId) {
      wx.showToast({ title: '题目ID不存在', icon: 'none' });
      return;
    }

    // 获取用户ID
    const userId = this.getUserId();
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    try {
      // 调用后端接口发布评论
      await http.post('/wjq/comment', {
        questionId: questionId,
        content: this.data.commentText,
        userId: userId
      });

      // 获取当前用户信息
      const userInfo = await userService.getUserInfo(userId);
      const displayName = userService.getDisplayName(userInfo);

      const newComment = {
        id: Date.now(),
        userId: userId,
        userName: displayName,
        content: this.data.commentText,
        createTime: new Date().toLocaleString(),
        displayName: '我' // 新发布的评论显示为"我"
      };

      // 更新评论列表
      this.setData({
        comments: [newComment, ...this.data.comments],
        commentText: ''
      });

      wx.showToast({ title: '评论发布成功', icon: 'success' });
    } catch (err) {
      console.error('发布评论失败:', err);
      wx.showToast({ title: '发布失败', icon: 'none' });
    }
  },

  /**
   * 获取用户ID
   */
  getUserId() {
    try {
      const { getUserId } = require('../../../utils/userManager.js');
      const userId = getUserId();

      if (userId) {
        return userId;
      } else {
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        });
        return null;
      }
    } catch (e) {
      console.error('获取用户ID失败:', e);
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none',
        duration: 2000
      });
      return null;
    }
  },

  /**
   * 获取评论列表
   */
  async fetchComments() {
    const currentQuestion = this.data.currentQuestion;
    const questionId = currentQuestion.id || currentQuestion.question_id;
    
    if (!questionId) {
      console.warn('题目ID不存在，无法获取评论');
      return;
    }

    try {
      // 调用后端接口获取评论列表
      const res = await http.get(`/wjq/comment/listByQuestionId/${questionId}`);

      if (res.data && Array.isArray(res.data)) {
        // 获取当前用户ID
        const currentUserId = this.getUserId();

        // 收集所有用户ID
        const userIds = [...new Set(res.data.map(comment => comment.userId).filter(Boolean))];

        // 批量获取用户信息
        const userInfoMap = new Map();
        if (userIds.length > 0) {
          const userInfos = await userService.getBatchUserInfo(userIds);
          userInfos.forEach(userInfo => {
            userInfoMap.set(userInfo.userId.toString(), userInfo);
          });
        }

        // 处理评论数据
        const processedComments = res.data.map(comment => {
          const isCurrentUser = comment.userId == currentUserId;

          if (isCurrentUser) {
            return {
              ...comment,
              displayName: '我'
            };
          } else {
            // 获取用户信息
            const userInfo = userInfoMap.get(comment.userId?.toString());
            const displayName = userService.getDisplayName(userInfo);

            return {
              ...comment,
              displayName: displayName
            };
          }
        });

        this.setData({
          comments: processedComments
        });
      } else {
        this.setData({
          comments: []
        });
      }
    } catch (err) {
      console.error('获取评论失败:', err);
      this.setData({
        comments: []
      });
    }
  },

  /**
   * 评论输入处理
   */
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  /**
   * 添加笔记
   */
  async addNote() {
    if (!this.data.noteText.trim()) {
      wx.showToast({ title: '请输入笔记内容', icon: 'none' });
      return;
    }

    const currentQuestion = this.data.currentQuestion;
    const questionId = currentQuestion.id || currentQuestion.question_id;

    if (!questionId) {
      wx.showToast({ title: '题目ID不存在', icon: 'none' });
      return;
    }

    try {
      // 获取用户ID
      const userId = this.getUserId();
      if (!userId) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        return;
      }

      // 调用后端接口保存笔记
      await noteService.saveNote({
        questionId: questionId,
        content: this.data.noteText,
        userId: userId
      });

      // 直接更新当前题目的笔记，而不是添加新笔记
      const updatedNote = {
        id: Date.now(),
        content: this.data.noteText,
        time: new Date().toLocaleString()
      };

      // 更新当前题目的笔记（只保留一条最新的笔记）
      const questions = [...this.data.questions];
      questions[this.data.currentIndex].notes = [updatedNote];

      this.setData({
        questions,
        currentQuestion: questions[this.data.currentIndex],
        noteText: '' // 保存后清空输入框
      });

      wx.showToast({ title: '笔记保存成功', icon: 'success' });
    } catch (err) {
      console.error('保存笔记失败:', err);
      wx.showToast({ title: '保存失败', icon: 'none' });
    }
  },

  /**
   * 笔记输入处理
   */
  onNoteInput(e) {
    this.setData({
      noteText: e.detail.value
    });
  },

  /**
   * 获取当前题目的笔记
   */
  async fetchNote() {
    const currentQuestion = this.data.currentQuestion;
    const questionId = currentQuestion.id || currentQuestion.question_id;

    if (!questionId) {
      console.warn('题目ID不存在，无法获取笔记');
      return;
    }

    try {
      const notes = await noteService.getNoteByQuestionId(questionId);
      const currentUserId = this.getUserId();

      // 过滤出当前用户的笔记
      const userNotes = notes.filter(note => note.userId == currentUserId);

      if (userNotes.length > 0) {
        // 取最新的笔记（按创建时间排序）
        const sortedNotes = userNotes.sort((a, b) => {
          const timeA = new Date(a.createTime || a.create_time || 0).getTime();
          const timeB = new Date(b.createTime || b.create_time || 0).getTime();
          return timeB - timeA; // 降序排列，最新的在前
        });
        const latestNote = sortedNotes[0];

        // 更新当前题目的笔记（只保留一条最新的笔记）
        const questions = [...this.data.questions];
        questions[this.data.currentIndex].notes = [{
          id: latestNote.id,
          content: latestNote.content,
          time: latestNote.createTime || latestNote.create_time || latestNote.updateTime || latestNote.update_time || new Date().toLocaleString()
        }];

        this.setData({
          questions,
          currentQuestion: questions[this.data.currentIndex],
          noteText: latestNote.content // 在输入框中显示现有笔记
        });
      } else {
        // 没有笔记，清空输入框和笔记列表
        const questions = [...this.data.questions];
        questions[this.data.currentIndex].notes = [];

        this.setData({
          questions,
          currentQuestion: questions[this.data.currentIndex],
          noteText: ''
        });
      }
    } catch (err) {
      console.error('获取笔记失败:', err);
      this.setData({
        noteText: ''
      });
    }
  },

  /**
   * 返回首页
   */
  goHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  /**
   * 分享
   */
  onShareAppMessage() {
    const { reportData } = this.data;
    return {
      title: `我在${reportData.questionBankName}中答对了${reportData.correct}/${reportData.total}题，正确率${reportData.correctRate}%！`,
      path: '/index/pages/questionAnalysis/questionAnalysis'
    };
  },

  /**
   * 标记正确选项
   */
  markCorrectOption(options, correctAnswer) {
    if (!correctAnswer || !Array.isArray(options)) {
      return options;
    }
    
    const markedOptions = options.map(option => {
      const isCorrect = option.label === correctAnswer;
      
      return {
        ...option,
        isCorrect: isCorrect
      };
    });
    
    return markedOptions;
  }
});
